package com.data.util

import java.security.MessageDigest
import java.security.SecureRandom
import java.util.*
import kotlin.experimental.and

object DatabaseIdUtils {
    private val SESSION_ID_BYTES = 16


    /**
     * 随机生成一个不重复的唯一UU id
     *
     * @return
     */
    val dataId: String
        @Synchronized get() = UUID.randomUUID().toString()

    /**
     * 生成一个10位数的唯一的个id，用于数据比较少的时候，
     *
     * @return
     */
    // 电脑休息1秒，免得重复了数据
    val dataIdOne: String
        @Synchronized get() {
            try {
                Thread.sleep(1)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }

            val currentTimeMillis = System.currentTimeMillis()
            return currentTimeMillis.toString()
        }
    /**
     * 生成一个唯一sessionId  与Tomcat的sessionId 计算方式相同
     */
    val sessionId: String
        @Synchronized get() {
            val md5 = MessageDigest.getInstance("MD5")
            val random = SecureRandom()  // 取随机数发生器, 默认是SecureRandom
            var bytes = ByteArray(SESSION_ID_BYTES)
            random.nextBytes(bytes) //产生16字节的byte
            bytes = md5.digest(bytes) // 取摘要,默认是"MD5"算法
            val result = StringBuffer()
            for (i in bytes.indices) {     //转化为16进制字符串
                val b1 = ((bytes[i] and 0xF).toInt() shr 4).toByte()
                val b2 = (bytes[i] and 0xF)
                if (b1 < 10)
                    result.append(('0' + b1.toInt()))
                else
                    result.append(('A' + (b1 - 10)))
                if (b2 < 10)
                    result.append(('0' + b2.toInt()))
                else
                    result.append(('A' + (b2 - 10)))
            }
            return result.toString()
        }


    @JvmStatic
    fun main(args: Array<String>) {
        println(sessionId)
    }
}

